<?php

namespace Lib;

final class MsgPush {

    /**
     * @desc 消息列表
     *
     * @param     $channel
     * @param int $page
     * @param int $perPage
     * @return array|bool
     */
    public static function msglist($channel, $page = 0, $perPage = 0) {
        $begin = $perPage * ($page - 1);
        $end   = $perPage * $page - 1;

        $key   = sprintf(\Lib\Consts::MESSAGE_PUSH, md5($channel));
        $redis = \Yaf\Registry::get('redis');
        $data  = $redis->lgetrange($key, $begin, $end);

        if($data === false) {
            return false;
        }

        $return = [];

        foreach($data as $value) {
            $return[] = unserialize($value);
        }

        return $return;
    }

    /**
     * @desc 添加消息
     *
     * @param $channel
     * @param $data
     * @return mixed
     */
    public static function msgadd($channel, $data) {
        $key   = sprintf(\Lib\Consts::MESSAGE_PUSH, md5($channel));
        $data  = serialize($data);
        $redis = \Yaf\Registry::get('redis');

        return $redis->lpush($key, $data);
    }

    /**
     * @desc 删除消息
     *
     * @param $channel
     * @return mixed
     */
    public static function msgdel($channel) {
        $key   = sprintf(\Lib\Consts::MESSAGE_PUSH, md5($channel));
        $redis = \Yaf\Registry::get('redis');

        return $redis->del($key);
    }

    /**
     * @desc 删除消息
     *
     * @param $channel
     * @return mixed
     */
    public static function msglen($channel) {
        $key   = sprintf(\Lib\Consts::MESSAGE_PUSH, md5($channel));
        $redis = \Yaf\Registry::get('redis');

        return $redis->llen($key);
    }

}
